# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        nodeA = headA
        countA = 0
        nodeB = headB
        countB = 0
        while nodeA:
            countA += 1
            nodeA = nodeA.next
        while nodeB:
            countB += 1
            nodeB = nodeB.next
        nodeA = headA
        nodeB = headB
        res = countA - countB
        if res > 0:
            for _ in range(res):
                nodeA = nodeA.next
        if res < 0:
            for _ in range(-res):
                nodeB = nodeB.next
        while nodeA:
            if nodeA == nodeB:
                return nodeA
            nodeA = nodeA.next
            nodeB = nodeB.next
        return None